#! /usr/bin/python
"""
utils.py
Only basic Function in here!
"""

import datetime
import sys
import os

logging = True # Forces logging (only for alpha development)
log_Callback = None
error_Callback = None

if logging:
	try:
		os.mkdir("logs")
	except:
		pass
	try:
		os.chdir("logs")
		logfile = open(datetime.datetime.now().strftime("%d_%m_%Y_%H_%M")+".log", "w")
		os.chdir("..")
	except:
		err("Failed to open create log-file!")


## This is the error handler. Every error should be passed through this function
def err(msg=""):
	log("ERROR: "+msg)
	if error_Callback != None:
		error_Callback(msg)
	exit()

## Writes messages in the log file
def log(msg=""):
	text = datetime.datetime.now().strftime("[%H:%M:%S]")+" "+msg
	print text
	if log_Callback != None:
		log_Callback(text+"\n")
	if logging:
		logfile.write(text+"\n")
	return

## This function is for a clean exit
def exit(status=0):
	log("exiting")
	if logging:
		logfile.close()
	sys.exit(status)

## This function deletes all logs
def deletelogs():
	os.chdir("logs")
	for i, j, dir in os.walk(os.getcwd()):
		for f in dir:
			if ".log" in f.lower():
				if f != logfile.name:
					# Don't delete the current logfile!
					os.remove(f)
	os.chdir("..")
	log("logs deleted")
